package com.kedacom.freedomLabel.view.activity.report;

import android.arch.lifecycle.ViewModelProviders;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.kedacom.freedomLabel.BR;
import com.kedacom.freedomLabel.Options;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseFragment;
import com.kedacom.freedomLabel.databinding.FragmentReportSummaryBinding;
import com.kedacom.freedomLabel.databinding.ItemProductSummaryBinding;
import com.kedacom.freedomLabel.model.bean.Business;
import com.kedacom.freedomLabel.model.bean.BusinessGroup;
import com.kedacom.freedomLabel.view.widget.MyDatePickerDialog;
import com.kedacom.freedomLabel.viewmodel.report.ReportSummaryViewModel;
import com.kedacom.lego.adapter.recyclerview.LegoBaseRecyclerViewAdapter;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.OnMessage;
import com.kedacom.lego.annotation.ViewModel;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@ContentView(R.layout.fragment_report_summary)
@ViewModel(ReportSummaryViewModel.class)
public class ReportSummaryFragment extends BaseFragment<FragmentReportSummaryBinding, ReportSummaryViewModel> {

    private List<BusinessGroup> businessGroups = new ArrayList<>();
    private LegoBaseRecyclerViewAdapter<BusinessGroup> adapter;
    public static int type = 0;
    private List<Business> productList = new ArrayList<>();
    private List<Business> operatorList = new ArrayList<>();
    private SimpleDateFormat sdf001 = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View root = super.onCreateView(inflater, container, savedInstanceState);
        mViewModel.reportType.setValue(type);

        mBinding.pre.setOnClickListener(v -> {
            if (mViewModel.reportType.getValue() == null)
                return;
            beep();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(mViewModel.currentDisplayDate.getValue());
            if (mViewModel.reportType.getValue() == 0) {
                // 上一天
                calendar.add(Calendar.DAY_OF_MONTH, -1);
            } else {
                // 上一月
                calendar.add(Calendar.MONTH, -1);
            }
            mViewModel.currentDisplayDate.setValue(calendar.getTime());
        });
        mBinding.next.setOnClickListener(v -> {
            if (mViewModel.reportType.getValue() == null)
                return;
            beep();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(mViewModel.currentDisplayDate.getValue());
            if (mViewModel.reportType.getValue() == 0) {
                // 下一天
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            } else {
                // 下一月
                calendar.add(Calendar.MONTH, 1);
            }
            mViewModel.currentDisplayDate.setValue(calendar.getTime());
        });

        mBinding.detail.setOnClickListener(v -> {
            if (getActivity() != null) {
                beep();
                ReportDetailFragment fragment = new ReportDetailFragment();
                Bundle bundle = new Bundle();
                bundle.putLong("startTime", mViewModel.startTime);
                bundle.putLong("endTime", mViewModel.endTime);
                bundle.putString("fileDir", sdf001.format(new Date()));
                if (mViewModel.reportType.getValue() == 0) {
                    bundle.putString("fileName", "day_report_" + sdf001.format(new Date(mViewModel.startTime)) + "_" + sdf001.format(new Date(mViewModel.endTime)) + ".xls");
                } else if (mViewModel.reportType.getValue() == 1) {
                    bundle.putString("fileName", "month_report_" + sdf001.format(new Date(mViewModel.startTime)) + "_" + sdf001.format(new Date(mViewModel.endTime)) + ".xls");
                }
                fragment.setArguments(bundle);
                FragmentTransaction f = getActivity().getSupportFragmentManager().beginTransaction();
                f.add(R.id.report_container, fragment);
                f.addToBackStack("report_detail").commit();
            }
        });

        mBinding.startDate.setOnClickListener(this::selectStartDate);

        mBinding.endDate.setOnClickListener(this::selectEndDate);

        mBinding.selectProduct.setOnClickListener(this::selectProduct);

        if (mViewModel.reportType.getValue() != null) {
            mBinding.detail.setVisibility(View.VISIBLE);
            if (mViewModel.reportType.getValue() == 0 || mViewModel.reportType.getValue() == 1) {
                mBinding.titleProductLayout.setVisibility(View.GONE);
                mBinding.contentProductLayout.setVisibility(View.GONE);
                mViewModel.currentDisplayDate.observe(this, queryDate -> {
                    mBinding.displayDate.setText(new SimpleDateFormat(
                            mViewModel.reportType.getValue() == 0 ? "yyyy-MM-dd" : "yyyy-MM", Locale.getDefault()).format(queryDate));
                    mViewModel.getSummary(); // 查询总览
                });
                // 重置时间
                mViewModel.currentDisplayDate.setValue(mViewModel.currentDate);
            } else if (mViewModel.reportType.getValue() == 2 || mViewModel.reportType.getValue() == 3) {
                mBinding.detail.setVisibility(View.GONE);
                mBinding.titleLayout.setVisibility(View.GONE);
                mBinding.contentLayout.setVisibility(View.GONE);

                mViewModel.startDate.observe(this, queryStartDate -> {
                    mBinding.startDate.setText(new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                            .format(queryStartDate));
                    mViewModel.getSummaryGroup();
                });
                mViewModel.endDate.observe(this, queryEndDate -> {
                    mBinding.endDate.setText(new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                            .format(queryEndDate));
                    mViewModel.getSummaryGroup();
                });

                // 重置时间
                mViewModel.startDate.setValue(mViewModel.currentDate);
                mViewModel.endDate.setValue(mViewModel.currentDate);

                mBinding.startDate.setTag(mViewModel.currentDate);
                mBinding.endDate.setTag(mViewModel.currentDate);

                mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                adapter = new LegoBaseRecyclerViewAdapter<BusinessGroup>(R.layout.item_product_summary, businessGroups, BR.group) {
                    @Override
                    protected void onCustomBindItem(ViewDataBinding binding, int position) {
                        super.onCustomBindItem(binding, position);
                        ((ItemProductSummaryBinding) binding).layout.setBackgroundColor(ContextCompat.getColor(getContext(),
                                position % 2 == 0 ? R.color.white_back : android.R.color.transparent));
                    }
                };
                adapter.setOnItemClickListener((view, group, index) -> {
                    beep();
                    ReportDetailFragment fragment = new ReportDetailFragment();
                    Bundle bundle = new Bundle();
                    bundle.putLong("startTime", mViewModel.startTime);
                    bundle.putLong("endTime", mViewModel.endTime);
                    bundle.putString("fileDir", sdf001.format(new Date()));
                    if (mViewModel.reportType.getValue() == 2) {
                        bundle.putString("productId", adapter.getData().get(index).product_id);
                        bundle.putString("fileName", "product_report_" + adapter.getData().get(index).name + "_" + sdf001.format(new Date(mViewModel.startTime)) + "_" + sdf001.format(new Date(mViewModel.endTime)) + ".xls");
                    } else if (mViewModel.reportType.getValue() == 3) {
                        bundle.putString("cardNumber", adapter.getData().get(index).product_id);
                        bundle.putString("fileName", "operator_report_" + adapter.getData().get(index).name + "_" + sdf001.format(new Date(mViewModel.startTime)) + "_" + sdf001.format(new Date(mViewModel.endTime)) + ".xls");
                    }
                    fragment.setArguments(bundle);
                    FragmentTransaction f = getActivity().getSupportFragmentManager().beginTransaction();
                    f.add(R.id.report_container, fragment);
                    f.addToBackStack("report_detail").commit();
                });
                mBinding.recyclerView.setAdapter(adapter);

                if (mViewModel.reportType.getValue() == 2) {
                    mBinding.labelSelectProduct.setText("产品名称：");
                    mBinding.labelProduct.setText("产品");
                    // 获取所有商品种类
                    mViewModel.getProductCategories();
                } else {
                    mBinding.labelSelectProduct.setText("操作员：");
                    mBinding.labelProduct.setText("操作员");
                    // 获取所有用户
                    mViewModel.getAllOperator();
                }

                // 默认查询所有种类的
                mViewModel.getSummaryGroup();
            }
        }

        mViewModel.businessCount.observe(this, businessCount -> {
            mBinding.count.setText(String.valueOf(businessCount.number));
            mBinding.weight.setText(String.valueOf(businessCount.weight));
        });

        mViewModel.businessGroup.observe(this, businessGroup -> {
            adapter.setData(businessGroup);
        });

        mViewModel.allProduct.observe(this, products -> {
            this.productList = products;
        });

        mViewModel.allOperator.observe(this, operators -> this.operatorList = operators);

        return root;
    }

    @OnMessage(Options.MSG_REFRESH_REPORT)
    public void refreshData() {
        if (mViewModel.reportType.getValue() != null) {
            mBinding.detail.setVisibility(View.VISIBLE);
            if (mViewModel.reportType.getValue() == 0 || mViewModel.reportType.getValue() == 1) {
                mViewModel.getSummary();
            } else if (mViewModel.reportType.getValue() == 2 || mViewModel.reportType.getValue() == 3) {
                mViewModel.getSummaryGroup();
            }
        }
    }

    public void selectStartDate(View view) {
        beep();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime((Date) view.getTag());

        new MyDatePickerDialog(getContext(),
                (view1, year, monthOfYear, dayOfMonth) -> {
                    Calendar temp = Calendar.getInstance();
                    temp.setTime((Date) view.getTag());
                    temp.set(Calendar.YEAR, year);
                    temp.set(Calendar.MONTH, monthOfYear);
                    temp.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                    if (temp.getTimeInMillis() > ((Date) mBinding.endDate.getTag()).getTime()) {
                        showToast("开始时间不能大于结束时间");
                    } else {
                        mViewModel.startDate.setValue(temp.getTime());
                        view.setTag(temp.getTime());
                    }
                },
                calendar.get(Calendar.YEAR), // Initial year selection
                calendar.get(Calendar.MONTH), // Initial month selection
                calendar.get(Calendar.DAY_OF_MONTH)
        ).show();
    }

    public void selectEndDate(View view) {
        beep();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime((Date) view.getTag());

        new MyDatePickerDialog(getContext(), (view12, year, month, dayOfMonth) -> {
            Calendar temp = Calendar.getInstance();
            temp.setTime((Date) view.getTag());
            temp.set(Calendar.YEAR, year);
            temp.set(Calendar.MONTH, month);
            temp.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            if (temp.getTimeInMillis() < ((Date) mBinding.startDate.getTag()).getTime()) {
                showToast("结束时间不能小于开始时间");
            } else {
                mViewModel.endDate.setValue(temp.getTime());
                view.setTag(temp.getTime());
            }
        },
                calendar.get(Calendar.YEAR), // Initial year selection
                calendar.get(Calendar.MONTH), // Initial month selection
                calendar.get(Calendar.DAY_OF_MONTH)
        )
                .show();
    }

    public void selectProduct(View view) {
        beep();
        String[] temp;

        if (mViewModel.reportType.getValue() == 2) {
            temp = new String[productList.size() + 1];
            temp[0] = "全部";
            for (int i = 0; i < productList.size(); i++) {
                temp[i + 1] = productList.get(i).name;
            }
        } else {
            temp = new String[operatorList.size() + 1];
            temp[0] = "全部";
            for (int i = 0; i < operatorList.size(); i++) {
                temp[i + 1] = operatorList.get(i).operator_name;
            }
        }

        new AlertDialog.Builder(getContext())
                .setTitle(mViewModel.reportType.getValue() == 2 ? "选择商品" : "选择操作员")
                .setItems(temp, (dialog, which) -> {
                    if (which == 0) {
                        if (mViewModel.reportType.getValue() == 2) {
                            mViewModel.productId = "";
                        } else {
                            mViewModel.cardNumber = "";
                        }
                    } else {
                        if (mViewModel.reportType.getValue() == 2) {
                            mViewModel.productId = productList.get(which - 1).product_id;
                        } else {
                            mViewModel.cardNumber = operatorList.get(which - 1).cardNumber;
                        }
                    }
                    mBinding.selectProduct.setText(temp[which]);
                    mViewModel.getSummaryGroup();
                })
                .show();
    }

    @Override
    public ReportSummaryViewModel getViewModel() {
        return ViewModelProviders.of(this).get(ReportSummaryViewModel.class);
    }
}
